/*
 * Copyright (C) 2012  E-dance Studio Harbin Institute of Technology 
 * Project:campusmobile
 * Author: 初楷博
 * Create Date: 2012-5-23下午02:34:48
 */
package hit.edance.campusmobile.chat.activity;

import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import hit.edance.campusmobile.chat.R;
import hit.edance.campusmobile.chat.database.DBLoginHelper;
import hit.edance.campusmobile.chat.model.ActivityKiller;
import hit.edance.campusmobile.chat.model.OfflineManager;
import hit.edance.campusmobile.chat.net.NetUtil;
import hit.edance.campusmobile.chat.service.CampusMobileService;
import hit.edance.campusmobile.chat.util.ConstantUtil;
import hit.edance.campusmobile.chat.util.SharedPreferencesHelper;
import hit.edance.campusmobile.chat.util.StringUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**   
 * 登录界面
 * 
 * @Project campusmobile
 * @Package hit.edance.campusmobile.chat.activity
 * @Class ActivityLogin
 * @Date 2012-5-23 下午02:34:48
 * @author 初楷博
 * @version 1.0
 * @since 1.0
 */
public class ActivityLogin extends Activity {
	
	private ProgressDialog pd; //登录进入对话框
	private String account, password, status; //账号、密码、隐身登陆标记
	private Handler myHandler;
	
	SharedPreferencesHelper sp;  
	
	DBLoginHelper loginDBHelper;
	
	boolean isAutoLogin = false; // 是否自动登陆标记
	//界面元素控件
	AutoCompleteTextView mAccount;
	EditText mPassword;
	ImageView mStatus,mAutoLogin;
	Button mLoginBtn,mRegisterBtn;
	TextView mStatusText,mAutoLoginText;
	
	//设置在线状态图标资源
	public static final int[] statusImg = {
			R.drawable.chat_presence_online,
			R.drawable.chat_presence_invisible,
			R.drawable.chat_presence_busy,
			R.drawable.chat_presence_away,
			R.drawable.chat_presence_offline
		};
	
	//设置在线状态描述String资源
	final int[] statusText = {
			R.string.chat_online,
			R.string.chat_invisible,
			R.string.chat_busy,
			R.string.chat_away,
			R.string.chat_offline
		};
	
	
	/* @see android.app.Activity#onCreate(android.os.Bundle)
	 *onCreate
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		ActivityKiller.addActivity(hashCode(), this);
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//设置无title模式
		setContentView(R.layout.chat_login); 
		myHandler = new Handler();
		loginDBHelper = new DBLoginHelper(this);
		sp = new SharedPreferencesHelper(this);
		initActivity();
		checkIfRemember();
		setAutoText();
	}


	/**
	 * 设置aotucompletetextview的adapter
	 */
	private void setAutoText() {

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line,
				loginDBHelper.getAccounts());
		mAccount.setAdapter(adapter);
	}

	/**
	 * 如果点击了自动登陆按钮，那么将自动读取缓存的账号密码并自动登陆
	 */
	private void checkIfRemember() {
		account = sp.getValueByKey("account");
		password = sp.getValueByKey("password");
		status = sp.getValueByKey("status","0");
		if(!"".equals(account) && !"".equals(password)){
			isAutoLogin = true;
			mAccount.setText(account);
			mPassword.setText(password);
			mStatus.setImageDrawable(getResources().getDrawable(statusImg[Integer.parseInt(status)]));
			mAutoLogin.setImageDrawable(getResources().getDrawable(R.drawable.chat_checkbox_on_background));

			login();	
		}
	}


	/**
	 * 登陆
	 */
	private void login() {
		account = mAccount.getEditableText().toString().trim();
		password = mPassword.getEditableText().toString().trim();
		if("".equals(account)||"".equals(password)){
			pd.dismiss();
			Toast.makeText(ActivityLogin.this, R.string.chat_toast1, Toast.LENGTH_SHORT).show();
			return;
		}
		//查看是否有可用连接
		if(!NetUtil.isNetworkAvailable(this)){
			Toast.makeText(ActivityLogin.this, R.string.chat_toast0, Toast.LENGTH_SHORT).show();
		}
		
		HandlerThread loginthread = new HandlerThread("login_thread");
		loginthread.start();
		final MyHandler handlerThread = new MyHandler(loginthread.getLooper());
		pd = ProgressDialog.show(ActivityLogin.this, getResources().getString(R.string.chat_toast2), getResources().getString(R.string.chat_toast3), true, true);
		handlerThread.post(new Runnable(){

			public void run() {
				try {
					if(CampusMobileService.connection.isConnected()&& CampusMobileService.connection != null){
						CampusMobileService.connection.disconnect();
					}
					CampusMobileService.connection.connect();
					CampusMobileService.connection.login(account, password);
						
					(handlerThread.obtainMessage()).sendToTarget();
				} 
				catch (XMPPException e) {
					pd.dismiss();
					Toast.makeText(ActivityLogin.this, R.string.chat_toast4, Toast.LENGTH_SHORT).show();
					try {
						Thread.sleep(2000);
					} catch (InterruptedException ie) {
						// TODO Auto-generated catch block
						ie.printStackTrace();
					}
					System.exit(1);
					e.printStackTrace();
				} 
				catch (IllegalStateException ie){
					pd.dismiss();
					if("Already logged in to server.".equals(ie.getMessage()))
						Toast.makeText(ActivityLogin.this, R.string.chat_toast5, Toast.LENGTH_SHORT).show();
					if("Not connected to server.".equals(ie.getMessage()))
						Toast.makeText(ActivityLogin.this, R.string.chat_toast6, Toast.LENGTH_SHORT).show();
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.exit(1);
				}
			}
		});
	}
	class MyHandler extends Handler{
		
		public MyHandler(Looper looper){
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			//login success
			loginDBHelper.insertAccount(account);
			sp.setValueByKey("account", isAutoLogin?account:null);
			sp.setValueByKey("password", isAutoLogin?password:null);
			sp.setValueByKey("status", isAutoLogin?status:null);
			
			ConstantUtil.JID = StringUtil.getLeftString(CampusMobileService.connection.getUser(), "/");
			ConstantUtil.STATUS = status;
			//获取离线消息
			 OfflineManager.getOfflineMessages();
			
			Presence presence = null;
			presence = new Presence(Presence.Type.available);
			presence.setStatus(status);
			CampusMobileService.connection.sendPacket(presence);

			pd.dismiss();
			startActivity(new Intent(ActivityLogin.this,ActivityTab.class));
			ActivityLogin.this.finish();
		}
    }

	/**
	 * activity初始化
	 */
	private void initActivity() {
		mAccount = (AutoCompleteTextView)findViewById(R.id.account);
    	mPassword = (EditText)findViewById(R.id.password); 
    	mStatus = (ImageView)findViewById(R.id.status_img);
    	mStatusText = (TextView)findViewById(R.id.status_text);
		mAutoLogin = (ImageView)findViewById(R.id.autologin_img);
		mAutoLoginText = (TextView)findViewById(R.id.autologin_text);
		mLoginBtn = (Button)findViewById(R.id.login);
		mRegisterBtn = (Button)findViewById(R.id.register);
		//设置监听器
		mStatus.setOnClickListener(l);
		mStatusText.setOnClickListener(l);
		mAutoLogin.setOnClickListener(l);
		mAutoLoginText.setOnClickListener(l);
		
		mLoginBtn.setOnClickListener(l);
	}
	private OnClickListener l = new OnClickListener(){

		public void onClick(View v) {
			int id = v.getId();
			if(id == mStatus.getId() || id == mStatusText.getId()){
				changeStatus();
			}else if(id == mAutoLogin.getId() || id == mAutoLoginText.getId()){
				isAutoLogin = isAutoLogin^false ? false : true;
				myHandler.post(new Runnable(){
					public void run() {
						int id = isAutoLogin ? R.drawable.chat_checkbox_on_background : R.drawable.chat_checkbox_off_background;
						mAutoLogin.setImageDrawable(getResources().getDrawable(id));
					}
					
				});
			}else if(id == mLoginBtn.getId()){
				login();
			}
		}
    	
    };
    private void changeStatus(){
    	StatusDialog statusDialog = new StatusDialog(ActivityLogin.this,R.style.chat_dialog);//创建Dialog并设置样式主题
		statusDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		Window win = statusDialog.getWindow();
		LayoutParams params = new LayoutParams();
		int[] location = new int[2];
		mStatus.getLocationOnScreen(location); 
		params.x = -1*(ConstantUtil.widthPixels/2-location[0])+(int)(90*ConstantUtil.density/2)-(int)(5*ConstantUtil.density);//设置x偏移坐标
		params.y = -1*(ConstantUtil.heightPixels/2-location[1])+(int)(135*ConstantUtil.density/2)-(int)(7.5*ConstantUtil.density);//设置y偏移坐标
		win.setAttributes(params);
		statusDialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭Dialog
		statusDialog.show();
    }
    class StatusDialog extends AlertDialog{

    	public StatusDialog(Context context, int theme) {
    	    super(context, theme);
    	}
    	
    	public StatusDialog(Context context){
    		super(context);
    	}

    	
    	
    	private ImageView imgonline,imginvisible,imgbusy,imgaway;
    	private TextView online,invisible,busy,away;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    	    super.onCreate(savedInstanceState);
            setContentView(R.layout.chat_statusdialog);
            
	    	imgonline = (ImageView)findViewById(R.id.presence_online);
	    	imginvisible = (ImageView)findViewById(R.id.presence_invisible);
	    	imgbusy = (ImageView)findViewById(R.id.presence_busy);
	    	imgaway = (ImageView)findViewById(R.id.presence_away);
	    
    	    online = (TextView)findViewById(R.id.online);
	    	invisible = (TextView)findViewById(R.id.invisible);
	    	busy = (TextView)findViewById(R.id.busy);
	    	away = (TextView)findViewById(R.id.away);
	    	
			imgonline.setOnClickListener(l);
			imginvisible.setOnClickListener(l);
			imgbusy.setOnClickListener(l);
			imgaway.setOnClickListener(l);
			
			online.setOnClickListener(l);
			invisible.setOnClickListener(l);
			busy.setOnClickListener(l);
			away.setOnClickListener(l);
    	    	
    	}
    	
    	private View.OnClickListener l = new View.OnClickListener(){

			public void onClick(View view) {
				int id = view.getId();
				if(id == imgonline.getId()||id == online.getId()){
					status = "0";
				}else if(id == imginvisible.getId()||id == invisible.getId()){
					status = "1";
				}else if(id == imgbusy.getId()||id == busy.getId()){
					status = "2";
				}else if(id == imgaway.getId()||id == away.getId()){
					status = "3";
				}
				myHandler.post(new Runnable(){

					public void run() {
						mStatus.setImageDrawable(getResources().getDrawable(statusImg[Integer.parseInt(status)]));
						mStatusText.setText(getResources().getString(statusText[Integer.parseInt(status)]));
					}
					
				});
				StatusDialog.this.dismiss();
			}
    	};
    	
    	
    }
    /* @see android.app.Activity#onDestroy()
	 *onDestroy
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		ActivityKiller.killActivityByHashCode(hashCode());
	}
}
